import { ref, reactive, toRaw, onMounted, h } from "vue";
import { addDialog } from "@/components/ReDialog";
import { message } from "@/utils/message";
import { vehicleUsageApi } from "@/api/business/vehicleUsage";
import { fuelApi } from "@/api/business/fuel";
import dayjs from "dayjs";
import * as XLSX from "xlsx";
const utils = XLSX.utils;
import {
	getKeyList,
	cloneDeep,
	isAllEmpty,
	deviceDetection
} from "@pureadmin/utils";
const exportQueryForm = reactive({
	type: 1,
	timeRange: []
});
const queryPrams = reactive({
	queryStartTime: dayjs().format("YYYY-MM-DD 00:00:00"),
	queryEndTime: dayjs().format("YYYY-MM-DD 23:59:59")
});
const queryFormRef = ref();
// 导出Excel核心函数
export const exportExcel = async (
	dataList: any[],
	columns: TableColumnList,
	type: string,
	queryPrams: Record<string, any> = {}
) => {
	if (!dataList.length) {
		message("暂无数据可导出", { type: "warning" });
		return;
	}
	const res = dataList.map(item => {
		const arr = [];
		columns.forEach(column => arr.push(item[column.prop as string]));
		return arr;
	});
	const titleList = columns.map(column => column.label);
	res.unshift(titleList);
	const workSheet = utils.aoa_to_sheet(res);
	const workBook = utils.book_new();
	utils.book_append_sheet(workBook, workSheet, "数据报表");
	const title = {
		carTotal: "用车统计记录",
		oil: "加油报表统计记录",
		car: "用车报表统计记录"
	};
	const fileName = `${dayjs(queryPrams.queryStartTime).format("YYYY-MM-DD")}至${dayjs(queryPrams.queryEndTime).format("YYYY-MM-DD")}${title[type]}.xlsx`;
	XLSX.writeFile(workBook, fileName);
	message("导出成功", { type: "success" });
};
// 导出对话框打开函数（需通过参数传递依赖的状态）
export const openExportDialog = (
	column: TableColumnList,
	type: string,
	tableData?: any
) => {
	addDialog({
		title: `选择时间段`,
		width: "40%",
		draggable: true,
		fullscreen: deviceDetection(),
		fullscreenIcon: true,
		closeOnClickModal: false,
		contentRenderer: () => (
			<div style= "padding: 20px; height: 100%; overflow-y: auto" >
			<el-form ref={ queryFormRef } model={ exportQueryForm } label- width="100px" >
	<el-form - item label = "时间范围" prop = "timeRange" >
	<el-radio - group
              modelValue = { exportQueryForm.type }
              onUpdate: modelValue = { val => (exportQueryForm.type = val)}
            >
	<el-radio - button label = "customTime" value = { 1} >
		今天
		</el-radio>
		< el - radio - button label = "thisWeek" value = { 7} >
			本周
			</>
			< el - radio - button label = "thisMonth" value = { 30} >
				近30天
				</>
				< el - radio - button label = "thisMonth" value = { 0} >
					自定义
					</>
					</el-radio-group>
					</el-form-item>
{
	exportQueryForm.type === 0 && (
		<el-form - item label = "选择开始范围" prop = "timeRange" >
			<el-date - picker
	modelValue = { exportQueryForm.timeRange }
	onUpdate: modelValue = { val => (exportQueryForm.timeRange = val)
}
range - separator="至"
start - placeholder="开始日期"
end - placeholder="结束日期"
format = "YYYY-MM-DD HH:mm:ss"
value - format="YYYY-MM-DD HH:mm:ss"
type = "datetimerange"
placeholder = "选择开始范围"
	/>
	</el-form-item>
          )}
</el-form>
	</div>
    ),
beforeSure: async (done, { options }) => {
	if (exportQueryForm.type === 1) {
		queryPrams.queryStartTime = dayjs().format("YYYY-MM-DD 00:00:00");
		queryPrams.queryEndTime = dayjs().format("YYYY-MM-DD 23:59:59");
	} else if (exportQueryForm.type === 7) {
		queryPrams.queryStartTime = dayjs()
			.startOf("week")
			.format("YYYY-MM-DD HH:mm:ss");
		queryPrams.queryEndTime = dayjs()
			.endOf("day")
			.format("YYYY-MM-DD 23:59:59");
	} else if (exportQueryForm.type === 30) {
		queryPrams.queryStartTime = dayjs()
			.subtract(30, "days")
			.format("YYYY-MM-DD 00:00:00");
		queryPrams.queryEndTime = dayjs()
			.subtract(1, "days")
			.format("YYYY-MM-DD 23:59:59");
	} else {
		queryPrams.queryStartTime = exportQueryForm.timeRange[0];
		queryPrams.queryEndTime = exportQueryForm.timeRange[1];
	}
	let curData = [];
	let result;
	switch (type) {
		case "car":
			result = await vehicleUsageApi.getListByGets(queryPrams);
			break;
		case "oil":
			result = await fuelApi.getFuelLists(queryPrams);
			break;
		case "totalCar":
			await vehicleUsageApi.getVehicleReport(toRaw(queryPrams));
			break;
	}
	console.log(result);
	if (result?.success) {
		curData = result.data;
		if (!curData) {
			message("暂无数据可导出", { type: "warning" });
			return;
		}
		// 校验表单后执行导出
		queryFormRef.value.validate(async valid => {
			if (valid) {
				await exportExcel(curData, column, type, queryPrams);
				await done();
			} else {
				message("表单验证失败", { type: "warning" });
			}
		});
	} else {
		message(result?.message || "导出失败", { type: "warning" });
	}
}
  });
};
// 根据传入column;动态处理导出excel表头和内容
